package com.example.order.service.impl;

import java.math.BigDecimal;
import java.net.URI;
import java.util.Arrays;
import java.util.List;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.example.order.feign.ProductFeignClient;
import com.example.order.pojo.Order;
import com.example.order.service.OrderService;
import com.example.product.pojo.Product;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    /**
     * 服务发现
     */
    @Autowired
    private DiscoveryClient discoveryClient;

    /**
     * 负载均衡
     */
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    /**
     * 远程调用
     */
    @Autowired
    private RestTemplate restTemplate;

    /**
     * Feign 远程调用客户端
     */
    @Resource
    private ProductFeignClient productFeignClient;

    /**
     * 声明资源
     * - 推荐 URL 资源用于接口级限流
     * - 方法名资源用于核心逻辑函数限流
     */
    @SentinelResource(value = "createOrder", blockHandler = "createOrderFallback") // 资源命名
    @Override
    public Order createOrder(Long productId, Long userId) {
        // Product product = getProductFromRemoteWithLoadBalanceAnnotation(productId);
        /**
         * 使用 Feign 完成远程调用
         */
        Product product = productFeignClient.getProductById(productId);
        Order order = new Order();
        order.setId(1L);
        order.setTotalAmount(product.getPrice().multiply(new BigDecimal(product.getNum()))); // 金额
        order.setUserId(userId);
        order.setNickName("trj");
        order.setAddress("AUST");
        order.setProductList(Arrays.asList(product)); // 商品列表
        return order;
    }

    /**
     * blockHandler 是专门用来处理 Sentinel规则触发后抛出的异常（也就是 BlockException 及其子类）的；
     * fallback 是用来处理业务逻辑中抛出的所有运行时异常（通常指 Throwable，如 NullPointerException、ArithmeticException、IOException 等）；
     * 👉 所以：
     * ✅ blockHandler 是 Sentinel 专属异常兜底
     * ✅ fallback 是业务异常通用兜底
     */
    /**
     * @SentinelResource：SentinelResourceAspect <p>
     * 业务方法兜底回调
     */
    public Order createOrderFallback(Long productId, Long userId, BlockException blockException) {
        Order order = new Order();
        order.setId(0L);
        order.setTotalAmount(new BigDecimal("0"));
        order.setUserId(userId);
        order.setNickName("未知用户");
        order.setAddress("异常信息：" + blockException.getClass() + "业务方法兜底回调");
        return order;
    }

    /**
     * 版本1：远程发送请求
     */
    public Product getProductFromRemote(Long productId) {
        // 1.获取商品服务所有URI
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        ServiceInstance instance = instances.get(0);
        URI uri = instance.getUri();
        String remoteUri = uri + "/product/" + productId;
        log.info("远程请求：{}", remoteUri);
        // 2.远程发送请求
        return restTemplate.getForObject(remoteUri, Product.class);
    }

    /**
     * 版本2：负载均衡远程发送请求
     */
    public Product getProductFromRemoteWithLoadBalance(Long productId) {
        // 1.获取商品服务所有URI
        ServiceInstance choose = loadBalancerClient.choose("service-product");
        URI uri = choose.getUri();
        String remoteUri = uri + "/product/" + productId;
        log.info("远程请求：{}", remoteUri);
        // 2.远程发送请求
        return restTemplate.getForObject(remoteUri, Product.class);
    }

    /**
     * 版本3：基于注解的负载均衡
     */
    public Product getProductFromRemoteWithLoadBalanceAnnotation(Long productId) {
        /**
         * 动态替换：service-product
         */
        String remoteUri = "http://service-product/" + productId;
        return restTemplate.getForObject(remoteUri, Product.class);
    }

}
